//
//  Watchlist_TableVC.m
//  KaChing_App
//
//  Created by Michael Hinds on 3/19/09.
//  Copyright 2009 University of Arkansas. All rights reserved.
//

#import "Watchlist_TableVC.h"
#import "Constants.h"
#import "AsyncImageView.h"

@implementation Watchlist_TableVC

@synthesize stockTickerLabel;
@synthesize currentPriceLabel;
@synthesize currentPriceChangeLabel;
@synthesize dataManager;
@synthesize watchlist;

/*
 - (id)initWithStyle:(UITableViewStyle)style {
 // Override initWithStyle: if you create the controller programmatically and want to perform customization that 
 // is not appropriate for viewDidLoad.
 if (self = [super initWithStyle:style]) {
 }
 return self;
 }
 */

- (void)viewDidLoad {
	//	//temporary code for testing purposes until we get the dataManager to be passed between views
	//	[dataManager release];
	//	DataManager *tempDataManager = [[DataManager alloc] initWithRemoteKey:@"abrade5989lap" AndUserID:10769];
	//	dataManager = [tempDataManager retain];
	//	[tempDataManager release];
	
	//debug
	NSLog(@"\n\nInside Watchlist!\nRemotekey: %@\nUserID: %d", [dataManager remoteKey], [dataManager userID]);
    
	self.navigationItem.rightBarButtonItem = self.editButtonItem;	// Puts the edit button as the right bar button item
	
	//get updated watchlist information and update the table view with the new data.
	[self refreshWatchlist];
	
	[super viewDidLoad];
	
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}


///* This method is entered before the view appears each time */
// - (void)viewWillAppear:(BOOL)animated 
//{
//	NSLog(@"Watchlist view!!! - The viewWillAppear method!");
//	
//	/* Refreshes the watchlist in order to display the most current list */
//	[self refreshWatchlist];
//	
//	[super viewWillAppear:animated];
//}

/*
 - (void)viewDidAppear:(BOOL)animated {
 [super viewDidAppear:animated];
 }
 */
/*
 - (void)viewWillDisappear:(BOOL)animated {
 [super viewWillDisappear:animated];
 }
 */
/*
 - (void)viewDidDisappear:(BOOL)animated {
 [super viewDidDisappear:animated];
 }
 */

/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}

/*
 ------------------------------------------------------------------------
 TableView methods
 ------------------------------------------------------------------------
 */
#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [watchlist count];
}


// Customize the appearance of table view cells. Called for each row
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
	[currencyFormatter setPositiveFormat:@"#,##0.00"];
	[currencyFormatter setNegativeFormat:@"#,##0.00"];
	
	static NSString *CellIdentifier = @"Cell";
	UITableViewCell *cell = (UITableViewCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
	/* If the current cell hasn't been created yet */
	if (cell == nil)
	{
		
		/* Create the cell */
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero 
									   reuseIdentifier:CellIdentifier] autorelease];
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		
		if (indexPath.row % 2 == 0){
			cell.contentView.backgroundColor = [UIColor customLightGray];
		}
		else{
			cell.contentView.backgroundColor = [UIColor whiteColor];
		}
		
		NSLog(@"STOCK TICKER LABEL RETAIN COUNT: %d", stockTickerLabel.retainCount);
		
		/* Memory Management: release label prior to recreating it */
		[stockTickerLabel release];
		
		/* Create the Stock Ticker label and add it to the cell */
		stockTickerLabel = [[UILabel alloc] initWithFrame:ticker];
		stockTickerLabel.textAlignment = UITextAlignmentLeft;
		stockTickerLabel.text = [self checkDisplayString:[(NSMutableDictionary *)[watchlist objectAtIndex:indexPath.row] valueForKey:@"ticker"]];
		stockTickerLabel.font = [UIFont boldSystemFontOfSize:16.0];
		stockTickerLabel.backgroundColor = [UIColor clearColor];
		stockTickerLabel.tag = stockTickerLabel_Tag;
		[cell.contentView addSubview:stockTickerLabel];
		
		/* Memory Management: release label prior to recreating it */
		[currentPriceChangeLabel release];
		
		/* Create the Current Price Change label and add it to the cell */
		currentPriceChangeLabel = [[UILabel alloc] initWithFrame:prChange];
		currentPriceChangeLabel.textAlignment = UITextAlignmentLeft;
		currentPriceChangeLabel.text = [self checkDisplayString:[NSString stringWithFormat:@"%@",[currencyFormatter stringFromNumber:[NSNumber numberWithFloat:[(NSNumber *)[(NSMutableDictionary *)[watchlist objectAtIndex:indexPath.row] valueForKey:@"lastChange"] floatValue]]]]];
		
		if([currentPriceChangeLabel.text floatValue] <= 0){
			currentPriceChangeLabel.textColor = [UIColor redColor];
		}
		else{
			currentPriceChangeLabel.textColor = [UIColor customGreen];
		}
		currentPriceChangeLabel.font = [UIFont boldSystemFontOfSize:10.0];
		currentPriceChangeLabel.lineBreakMode = UILineBreakModeWordWrap;
		currentPriceChangeLabel.backgroundColor = [UIColor clearColor];		
		currentPriceChangeLabel.tag = currentPriceChangeLabel_Tag;
		[cell.contentView addSubview:currentPriceChangeLabel];		
		
		/* Memory Management: release label prior to recreating it */
		[currentPriceLabel release];
		
		/* Create the Current Price label and add it to the cell */	
		currentPriceLabel = [[UILabel alloc] initWithFrame:priceWL];
		currentPriceLabel.textAlignment = UITextAlignmentRight;
		currentPriceLabel.text =[self checkDisplayString:[NSString stringWithFormat:@"$%@  ",[currencyFormatter stringFromNumber:[NSNumber numberWithFloat:[(NSNumber *)[(NSMutableDictionary *)[watchlist objectAtIndex:indexPath.row] valueForKey:@"lastPrice"] floatValue]]]]];
		currentPriceLabel.backgroundColor = [UIColor clearColor];
		currentPriceLabel.textColor = [UIColor blackColor];
		currentPriceLabel.font = [UIFont boldSystemFontOfSize:16.0];
		currentPriceLabel.lineBreakMode = UILineBreakModeWordWrap;
		currentPriceLabel.tag = currentPriceLabel_Tag;
		[cell.contentView addSubview:currentPriceLabel];
		
		[currencyFormatter release];
    }
	
	/* The cell already exists (i.e., we are updating the content of an already-existing cell */
	else
	{
		if (indexPath.row % 2 == 0){
			cell.contentView.backgroundColor = [UIColor customLightGray];
		}
		else{
			cell.contentView.backgroundColor = [UIColor whiteColor];
		}
		
		/* Retrieve the new Stock Ticker and assign it to the stock ticker label */
		UILabel *tempTickerLabel = (UILabel *) [cell.contentView viewWithTag:stockTickerLabel_Tag];
		tempTickerLabel.text = [self checkDisplayString:[(NSMutableDictionary *)[watchlist objectAtIndex:indexPath.row] valueForKey:@"ticker"]];
		
		/* Retrieve the current price of the new Stock and assign it to the current price label */
		UILabel *tempPriceLabel = (UILabel *) [cell.contentView viewWithTag:currentPriceLabel_Tag];
		tempPriceLabel.text = [self checkDisplayString:[NSString stringWithFormat:@"$%@  ",[currencyFormatter stringFromNumber:[NSNumber numberWithFloat:[(NSNumber *)[(NSMutableDictionary *)[watchlist objectAtIndex:indexPath.row] valueForKey:@"lastPrice"] floatValue]]]]];
		
		/* Retrieve the current price change of the new Stock and assign it to the current price change label */
		UILabel *tempChangeLabel = (UILabel *) [cell.contentView viewWithTag:currentPriceChangeLabel_Tag];
		tempChangeLabel.text = [self checkDisplayString:[NSString stringWithFormat:@"%@",[currencyFormatter stringFromNumber:[NSNumber numberWithFloat:[(NSNumber *)[(NSMutableDictionary *)[watchlist objectAtIndex:indexPath.row] valueForKey:@"lastChange"] floatValue]]]]];
		if([tempChangeLabel.text floatValue] <= 0){
			tempChangeLabel.textColor = [UIColor redColor];
		}
		else{
			tempChangeLabel.textColor = [UIColor customGreen];
		}
	}
	/*Code to add in the new image to the cell*/
	//Create new frome for the image
	CGRect frame;
	
	//specify frame size
	frame.size.width=20; frame.size.height=20;
	
	//specify location of frame within cell
	frame.origin.x=0; frame.origin.y=5;
	
	//create a new asynchronous image object 
	AsyncImageView* asyncImage = [[[AsyncImageView alloc]
								   initWithFrame:frame] autorelease];
	
	//set the tag so that we know the image has been added
	asyncImage.tag = 999;
	
	//get the stock image url
	if([[watchlist objectAtIndex:indexPath.row] valueForKey:@"companyIconUrl"]!= NULL)
	{
		NSURL* url = [NSURL URLWithString:(NSString *) [[watchlist objectAtIndex:indexPath.row] valueForKey:@"companyIconUrl"]];
		
		[asyncImage loadImageFromURL:url];
		
		[cell.contentView addSubview:asyncImage];
	}
    /* Return the newly created (or newly updated) cell */
    return cell;
	
	/* This was creatd at the start of this method, therefore release it */
	[currencyFormatter release];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

- (void)tableView:(UITableView *)tv commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    // If row is deleted, remove it from the list.
    if (editingStyle == UITableViewCellEditingStyleDelete) 
	{
		NSString *ticker_2_Remove = [(UILabel *)[[[tv cellForRowAtIndexPath:indexPath] contentView] viewWithTag:stockTickerLabel_Tag] text];
		NSLog(@"The ticker to be removed: %@", ticker_2_Remove); 
		
		/* Remove the selected ticker from the watch list */
		[dataManager removeFromWatchList:ticker_2_Remove];	// Removes from profile (KaChing API call)
        [tv deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];	// Removes from table
		
		/* Reloads (i.e. refreshes the table) to account for the newly removed stock */
		[self refreshWatchlist];
    }
}

/*
 ------------------------------------------------------------------------
 IBAction methods
 ------------------------------------------------------------------------
 */
#pragma mark IBAction methods

- (IBAction) refreshWatchlist
{
	//Debug
	NSLog(@"Entered refresh Watchlist method.");
	
	/* Creates an ActivityIndicator and adds it to the middle of the screen */
	CGRect frame = CGRectMake(140.0, 200.0, activityIndicatorySize, activityIndicatorySize);
	UIActivityIndicatorView *progressInd = [[UIActivityIndicatorView alloc] initWithFrame:frame];		
	progressInd.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
	[self.navigationController.view addSubview:progressInd];
	
	[progressInd startAnimating];	// Start the animation of the ActivityIndicator
	
	/* If the DataManager exists (should always be the case if this method is called)... */
	if (dataManager != nil)
	{
		/* Retrieve all stock information. NOTE: This is what actually performs the Kaching network call */
		NSDictionary *watchlistDictionary = [[[dataManager getWatchlist] objectForKey:@"watchlist"] retain];
		
		//test
		NSMutableArray *tempWatchlist_Array = [[NSMutableArray alloc] init];
		
		NSArray *watchlistStockNames_Unsorted = [watchlistDictionary allKeys];	// Get all short stocks in profile (unsorted)
		
		/* Sort the stocks in alphabetical order and store them in another array */
		NSArray *watchlistStockNames_Sorted = [watchlistStockNames_Unsorted sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
		
		/* Loop through all stocks in the dictionary */
		for(int i = 0; i < [watchlistStockNames_Sorted count]; i++)
		{
			NSString *key = [watchlistStockNames_Sorted objectAtIndex:i];	// The current Stock name
			
			//assign the value at key into the watchlist
			[tempWatchlist_Array addObject:(NSMutableDictionary *)[watchlistDictionary objectForKey:key]];
			
			//Debug
			NSLog(@"Watchlist array count: %d", [tempWatchlist_Array count]);
			NSLog(key);
			
			//add the ticker field to each Stock Dictionary along the the ticker value (which is key in this case)
			[(NSMutableDictionary *)[watchlistDictionary objectForKey:key] setObject:key forKey:@"ticker"];
		}
		
		watchlist = [tempWatchlist_Array retain];
		[tempWatchlist_Array release];
	}
	
	// Stop the animation of and release the ActivityIndicator
	[progressInd stopAnimating];
	[progressInd release];
	
	//rebuild the table data
	[self.tableView reloadData];
	
	//Debug
	NSLog(@"Leaving refreshWatchlist method and watchlist array is: %@", watchlist);
	NSLog(@"Watchlist array count: %d", [watchlist count]);
}

/*
 ------------------------------------------------------------------------
 Private methods
 ------------------------------------------------------------------------
 */
#pragma mark Private methods

//checks a string to be displayed to determine whether the string is null.
//if the string is null, then it changes it to -- for display purposes.
-(NSString *) checkDisplayString:(NSString *) data
{
	if(data == nil)
	{
		return @"--";
	}
	else
	{
		return data;
	}
}

/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */


/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
 }   
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }   
 }
 */


/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */


/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */


- (void)dealloc {//
	
	//memory management: all instance variables must be released in order to maintain proper retain counts.
	[stockTickerLabel release];
	[currentPriceLabel release];
	[currentPriceChangeLabel release];
	[dataManager release];
	[watchlist release];
    [super dealloc];
}

@end

